package com.ygswglxt.salary.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ygswglxt.salary.entity.SalaryRecord;
import com.ygswglxt.salary.mapper.SalaryMapper;
import com.ygswglxt.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

@Service
public class SalaryService {
    
    @Autowired
    private SalaryMapper salaryMapper;
    
    public Result<List<SalaryRecord>> getMySalary(Long userId) {
        // 使用联表查询，包含员工名称
        List<SalaryRecord> records = salaryMapper.selectByUserIdWithUserName(userId);
        return Result.success(records);
    }
    
    public Result<List<SalaryRecord>> getAllSalary() {
        // 使用联表查询，包含员工名称
        List<SalaryRecord> records = salaryMapper.selectAllWithUserName();
        return Result.success(records);
    }
    
    // 获取团队薪资（经理查看）
    public Result<List<SalaryRecord>> getTeamSalary(Long managerId) {
        // 简化处理：返回所有薪资记录（包含员工名称）
        // 实际应该根据组织架构查询下属的薪资
        // 这里暂时返回所有记录，后续可以根据managerId查询下属
        List<SalaryRecord> records = salaryMapper.selectTeamSalaryWithUserName();
        return Result.success(records);
    }
    
    public Result<String> createSalary(SalaryRecord salaryRecord) {
        // 验证必填字段
        if (salaryRecord.getUserId() == null) {
            return Result.error("用户ID不能为空");
        }
        if (salaryRecord.getMonth() == null || salaryRecord.getMonth().isEmpty()) {
            return Result.error("月份不能为空");
        }
        
        // 设置默认值
        if (salaryRecord.getBaseSalary() == null) {
            salaryRecord.setBaseSalary(BigDecimal.ZERO);
        }
        if (salaryRecord.getBonus() == null) {
            salaryRecord.setBonus(BigDecimal.ZERO);
        }
        if (salaryRecord.getDeduction() == null) {
            salaryRecord.setDeduction(BigDecimal.ZERO);
        }
        
        // 计算实发工资：基本工资 + 奖金 - 扣除
        BigDecimal total = salaryRecord.getBaseSalary()
                .add(salaryRecord.getBonus())
                .subtract(salaryRecord.getDeduction());
        
        // 确保实发工资不为负数
        if (total.compareTo(BigDecimal.ZERO) < 0) {
            total = BigDecimal.ZERO;
        }
        
        salaryRecord.setTotal(total);
        salaryMapper.insert(salaryRecord);
        return Result.success("薪资记录创建成功");
    }
    
    // 更新薪资记录
    public Result<String> updateSalary(Long id, SalaryRecord salaryRecord) {
        SalaryRecord existing = salaryMapper.selectById(id);
        if (existing == null) {
            return Result.error("薪资记录不存在");
        }
        
        // 更新字段
        if (salaryRecord.getMonth() != null && !salaryRecord.getMonth().isEmpty()) {
            existing.setMonth(salaryRecord.getMonth());
        }
        if (salaryRecord.getBaseSalary() != null) {
            existing.setBaseSalary(salaryRecord.getBaseSalary());
        }
        if (salaryRecord.getBonus() != null) {
            existing.setBonus(salaryRecord.getBonus());
        }
        if (salaryRecord.getDeduction() != null) {
            existing.setDeduction(salaryRecord.getDeduction());
        }
        
        // 重新计算实发工资
        BigDecimal total = existing.getBaseSalary()
                .add(existing.getBonus())
                .subtract(existing.getDeduction());
        if (total.compareTo(BigDecimal.ZERO) < 0) {
            total = BigDecimal.ZERO;
        }
        existing.setTotal(total);
        
        salaryMapper.updateById(existing);
        return Result.success("薪资记录更新成功");
    }
    
    // 导出薪资记录
    public void exportSalaryRecords(HttpServletResponse response, Long userId, String month) throws Exception {
        QueryWrapper<SalaryRecord> wrapper = new QueryWrapper<>();
        if (userId != null) {
            wrapper.eq("user_id", userId);
        }
        if (month != null && !month.isEmpty()) {
            wrapper.eq("month", month);
        }
        wrapper.orderByDesc("month", "create_time");
        
        List<SalaryRecord> records = salaryMapper.selectList(wrapper);
        
        // 准备导出数据
        List<Map<String, Object>> exportData = new ArrayList<>();
        SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        for (SalaryRecord record : records) {
            Map<String, Object> row = new HashMap<>();
            row.put("userName", record.getUserName() != null ? record.getUserName() : "员工" + record.getUserId());
            row.put("month", record.getMonth() != null ? record.getMonth() : "");
            row.put("baseSalary", record.getBaseSalary() != null ? record.getBaseSalary().toString() : "0.00");
            row.put("bonus", record.getBonus() != null ? record.getBonus().toString() : "0.00");
            row.put("deduction", record.getDeduction() != null ? record.getDeduction().toString() : "0.00");
            row.put("total", record.getTotal() != null ? record.getTotal().toString() : "0.00");
            row.put("createTime", record.getCreateTime() != null ? dateTimeFormat.format(record.getCreateTime()) : "");
            
            exportData.add(row);
        }
        
        // 表头
        String[] headers = {"员工姓名", "月份", "基本工资", "奖金", "扣除", "实发工资", "创建时间"};
        String[] fieldNames = {"userName", "month", "baseSalary", "bonus", "deduction", "total", "createTime"};
        
        // 导出Excel
        String fileName = "薪资记录";
        if (month != null && !month.isEmpty()) {
            fileName += "_" + month;
        }
        com.ygswglxt.salary.util.ExcelExportUtil.exportExcel(
            response, 
            fileName, 
            headers, 
            exportData, 
            fieldNames
        );
    }
}

